import { LoginWechat } from '@/service/db_index'
import { ConcatPhoneByCode, GetGenerateUserSig, GetPreferencesQueryByUserId, UserInfoQueryUser } from '@/service/db_user'
import { User } from '@/service/types/user'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useToast } from 'wot-design-uni'
// import { TUILogin } from '@tencentcloud/tui-core'
import { GetUserActivityInfoQueryByUser } from '@/service/db_activity'
import { Activity } from '@/service/types/activity'
import { GetQueryByUserId } from '@/service/db_feature'

const initState = {
  username: '', 
  avatar: '',
  personAvatar: { preUrl: '' } as User.Collect,
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<Optional<User.UserInfoQueryUserDetail>>({ ...JSON.parse(JSON.stringify(initState)) });
    const activityInfo = ref({} as Activity.ActivityInfo);
    const matchmakerInfo = ref({} as User.MatchmakerInfo);
    const loginSubmit = ref(false);
    const loginTime = ref(0);
    const token = ref('');
    const toast = useToast();
    const instrId = ref(''); // 介绍人id
    const source = ref(''); // 是否从红包分享进来
    /** IM 登录凭证 */
    const userSig = ref('');
    const heightInfo = reactive({
      height: 0,
      weight: 0,
      school: {
        label: '',
        value: ''
      },
      profession: {
        label: '',
        value: ''
      }
    })
    const activityHeightInfo = reactive({
      height: 0,
      weight: 0,
    })

    /** 获取用户信息 */
    const getUserInfo = async (options = {} as { 
      isLogin?: boolean; 
      id?: string 
    }, callback = () => {}) => {
      const { isLogin = false, id = userInfo.value.id } = options || {};
      try {
        const res = await UserInfoQueryUser({ id });
        console.log('获取用户信息UserInfoQueryUser', res)
        userInfo.value = res.data || {};
        callback && callback();
        getUserActivityInfo();

        userInfo.value.matchmakerFlag && getQueryByUserId();
        
        isLogin && handleTUILogin();
      } catch (error) {
        console.log(error);
      }
    }
    
    // 获取用户红娘信息
    const getQueryByUserId = async (callback = (data?: User.MatchmakerInfo) => {}) => {
      try {
        const res = await GetQueryByUserId({
          userId: userInfo.value.id
        });
        console.log('获取用户红娘信息GetQueryByUserId', res)
        const data = res.data || {} as User.MatchmakerInfo;
        matchmakerInfo.value = data;
        callback && callback(data);
      } catch (error) {
        console.log(error)
      }
    }

    /** 获取用户活动信息表详情 */
    const getUserActivityInfo = async (callback = () => {}) => {
      try {
        const res = await GetUserActivityInfoQueryByUser({ 
          userId: userInfo.value.id,
        });
        console.log('获取用户活动信息表详情GetUserActivityInfoQueryByUser', res)
        activityInfo.value = res.data || {} as Activity.ActivityInfo;
        callback && callback();
      } catch (error) {
        console.log(error);
      }
    }

    // IM登录
    const handleTUILogin = () => {
      // getGenerateUserSig((res) => {
      //   TUILogin.login({
      //     SDKAppID: 1600057360,
      //     userID: userInfo.value.id, 
      //     userSig: userSig.value, 
      //     useUploadPlugin: true,
      //     framework: 'vue3'
      //   }).catch(() => {});
      // });
    }

    /** IM登出 */
    const handleTUILogout = () => {
      // let promise = TUILogin.logout && TUILogin.logout();
      // promise.then(() => {
      //   // 登出成功后进行相关业务逻辑处理
      // })
    }

    // 设置token
    const setToken = (val: string) => {
      token.value = val;
      loginTime.value = +new Date();
    }

    // 设置用户信息
    const setUserInfo = (val: User.UserInfoQueryUserDetail) => {
      userInfo.value = val;
    }

    // 清空用户信息
    const clearUserInfo = () => {
      userInfo.value = { ...JSON.parse(JSON.stringify(initState)) };
      token.value = '';
      userSig.value = '';
      
      activityInfo.value = {} as Activity.ActivityInfo;
      matchmakerInfo.value = {} as User.MatchmakerInfo;
      preferencesDetail.value = {} as User.PreferencesDetail;

      heightInfo.height = 0;
      heightInfo.weight = 0;
      heightInfo.school = {
        label: '',
        value: ''
      };
      heightInfo.profession = {
        label: '',
        value: ''
      };

      activityHeightInfo.height = 0;
      activityHeightInfo.weight = 0;
    }

    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...JSON.parse(JSON.stringify(initState)) };
    }

    // 是否登录
    const isLogined = computed(() => !!token.value)

    const wxLogin = (callback = () => {}, phone = '') => {
      uni.showLoading({
        title: '登陆中...'
      });
      uni.login({
        "provider": "weixin",
        "onlyAuthorize": true, // 微信登录仅请求授权认证
        success: function(event){
          const { code } = event;
          // return console.log('code: ----', code)
          sendWxLogin(code, callback, phone);
        },
        fail: function (err) {
          setTimeout(() => {
            uni.hideLoading();
          }, 1000)
          // 登录授权失败
          // err.code是错误码
          console.log('登录授权失败err', err)
        }
      })
    }

    /** 发送登录请求 */
    const sendWxLogin = async (code, callback, phone = '') => {
      try {
        console.log('sendWxLogin instrId.value :', instrId.value, source.value)
        const data: any = { code, phone };
        instrId.value && (data.instrId = instrId.value);
        source.value && (data.source = source.value);
        const res = await LoginWechat(data);
        setToken(res.data.token);
        getUserInfo({ id: res.data.id, isLogin: true });
        uni.hideLoading();
        toast.show(res.message);
        callback && callback(res);
      } catch (error) {
        console.log('LoginWechat error', error)
        setTimeout(() => {
          uni.hideLoading();
        }, 1000)
      }
    }

    /** 获取IM用户凭证 */
    const getGenerateUserSig = async (callback) => {
      try {
        const res = await GetGenerateUserSig({
          userId: userInfo.value.id
        })
        userSig.value = res.data || '';
        callback && callback(res);
      } catch (error) {
        console.log(error)
      }
    }

    // 获取手机号
    const getphonenumber = async (res) => {
      if (res.errMsg === 'getPhoneNumber:fail user deny') return;
      try {
        const _res = await ConcatPhoneByCode({
          userId: userInfo.value.id,
          code: res.code
        })
        if(_res.code != 200) return toast.show(_res.message);
        getUserInfo({
          id: _res.data || ''
        });
      } catch (error) {
        console.log(error);
      }
    }

    const preferencesDetail = ref({} as User.PreferencesDetail);
    /** 获取用户择偶要求表详情 */
    const getPreferencesQueryByUserId = async (callback = () => {}) => {
      try {
        const res = await GetPreferencesQueryByUserId({
          userId: userInfo.value.id
        })
        preferencesDetail.value = res.data || {} as User.PreferencesDetail;
        callback && callback();
      } catch (error) {
        console.log(error)
      }
    }

    // 获取用户信息的vo
    const getUseVo = computed(() => {
      const { 
        identityVerificationVo,
        userBehaviorInfoStatisticsVo,
        userMembershipInfoVo,
        userProfileInfoVo,
        userSettingsInfoVo,
        personAvatar
      } = userInfo.value || {};

      return {
        identityVerificationVo: identityVerificationVo || {} as User.IdentityVerificationVo,
        userBehaviorInfoStatisticsVo: userBehaviorInfoStatisticsVo || {} as User.UserBehaviorInfoStatisticsVo,
        userMembershipInfoVo: userMembershipInfoVo || {} as User.UserMembershipInfoVo,
        userProfileInfoVo: userProfileInfoVo || {} as User.UserProfileInfoVo,
        userSettingsInfoVo: userSettingsInfoVo || {} as User.UserSettingsInfoVo,
        personAvatar: personAvatar || {} as User.Collect
      }
    })

    return {
      token,
      instrId,
      source,
      userSig,
      userInfo,
      isLogined,
      getUseVo,
      preferencesDetail,
      heightInfo,
      activityHeightInfo,
      activityInfo,
      matchmakerInfo,
      loginTime,
      loginSubmit,
      setToken,
      getUserInfo,
      setUserInfo,
      clearUserInfo,
      getGenerateUserSig,
      getQueryByUserId,
      reset,
      wxLogin,
      handleTUILogin,
      getphonenumber,
      handleTUILogout,
      getPreferencesQueryByUserId,
      getUserActivityInfo,
    }
  },
  {
    persist: true,
  },
)
